/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.unice.miage.oobdoo.manager;

import com.unice.miage.oobdoo.entity.Album;
import com.unice.miage.oobdoo.entity.Commentaire;
import com.unice.miage.oobdoo.entity.Photo;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * @author Jeremy Romano
 */
@Stateless
public class PhotoManager {
    
    @PersistenceContext
    private EntityManager em;

    /**
     * Creation d'une photo
     * @param album - l'album contenant la photo
     * @param nom - le nom de la photo
     * @param description - la description de la photo
     * @param pathFile - le path d'emplacement de la photo
     * @param pathThumb - le path d'emplacement de la miniature de la photo
     * @return la photo creee
     */
    public Photo creerPhoto(Album album, String nom, String description, String pathFile, String pathThumbHome, String pathThumbList, String pathThumbPhoto)
    {
        Photo p = new Photo(album, nom, description, pathFile, pathThumbHome, pathThumbList, pathThumbPhoto);
        em.persist(p);
        return p;
    }

    /**
     * Renvoie une photo selon son id
     * @param id - l'id de la photo
     * @return la photo
     */
    public Photo getPhotoById(int id)
    {
        Photo p = em.find(Photo.class, id);
        return p;
    }

    public Photo updateName(Photo p , String name)
    {
        p.setNom(name);
        em.merge(p);
        return p;
    }

    public Photo updateDescription(Photo p , String desc)
    {
        p.setDescription(desc);
        em.merge(p);
        return p;
    }

    public void addCommentaire(Photo p, Commentaire c)
    {
        p.addCommentaire(c);
        em.merge(p);
    }
    
    public void deletePhoto(Photo p)
    {
        try {
            em.remove(em.merge(p));
        } catch (Exception ex) {
            System.err.println("PhotoManager.deletePhoto, exception=" + ex);
        }
    }
    
    public void deleteCommentaire(Photo p, Commentaire c)
    {
        Collection<Commentaire> commentaires = p.getCommentaires();

        for (Commentaire com : commentaires) {
            if (com.getId() == c.getId()) {
                commentaires.remove(com);
                break;
            }
        }
        em.merge(p);
    }
 
}
